﻿using System.Web;
using RN.ERP.Web.BasicService;
using System.Configuration;
using System;
using Newtonsoft.Json;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Linq;

namespace RN.ERP.Web.Message
{
    /// <summary>
    /// 消息推送模块
    /// 处理消息的接收，分发，管理
    /// </summary>
    public class MsgPushHandler : IHttpHandler, IRequiresSessionState
    {
        #region Params

        private int AppID
        {
            get
            {
                return int.Parse(ConfigurationManager.AppSettings["AppId"]);
            }
        }

        private HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }

        private HttpResponse Response
        {
            get
            {
                return HttpContext.Current.Response;
            }
        }

        private BasicServiceClient bsc = new BasicServiceClient();

        private SessionUserInfo _user = null;
        private SessionUserInfo User
        {
            get
            {
                if(_user==null)
                    _user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
                return _user;
            }
        }
                
        private string Sender
        {
            get
            {
                return Request["Sender"];
            }
        }

        private DateTime? LastSearchTime
        {
            set
            {
                HttpContext.Current.Session["LastSearchTime"] = value;
            }
            get
            {
                var lst = HttpContext.Current.Session["LastSearchTime"];
                if (Request["IsPageLoad"] == "true" || lst == null)
                    return null;
                else
                    return (DateTime)lst;
            }
        }

        #endregion

        public void ProcessRequest(HttpContext context)
        {
            FuncRoute();
        }

        #region 处理方法

        /// <summary>
        /// 函数路由
        /// </summary>
        private void FuncRoute()
        {
            string func = Request["func"] ?? "";
            try
            {
                switch (func.ToLower())
                {
                    case "send":
                        SendMsg(); break;
                    case "getusers":
                        GetMsgUsers(); break;
                    case "getsentmsgs":
                        GetSentMsgs(); break;
                    case "deletemsgs":
                        MsgsDelete(); break;
                    case "getletterbrief":
                        GetLetterBrief();break;
                    case "receiveall":
                    default:
                        ReceiveAll(); break;
                }
            }
            catch (Exception ex)
            {
                Print("{'error':'"+ex.Message+"'}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        private void SendMsg()
        {
            BasicServiceClient bsc = new BasicServiceClient();
            try
            {
                T_Msg_SentMsg msg = new T_Msg_SentMsg
                {
                    AppID = AppID,
                    Sender = User.CorpUserGuid,
                    Receiver = Request["Users"],
                    SendTime = DateTime.Now,
                    State = 0,
                    MsgText = Request["MsgText"],
                    AreaCode = User.CurrentArea
                };
                msg.MsgType = 0;
                bsc.Send(msg);
                Print("success");
            }
            catch (Exception ex)
            {
                Print("fail");
            }
        }

        /// <summary>
        /// 获取所有未读信息
        /// </summary>
        private void ReceiveAll()
        {
            DateTime searchTime = DateTime.Now;
            var MsgList = bsc.GetMsgs(User.CorpUserGuid, null, AppID, LastSearchTime, false, false, User.CurrentArea);
            LastSearchTime = searchTime;
            Print(JsonConvert.SerializeObject(MsgList));
        }

        /// <summary>
        /// 响应请求
        /// </summary>
        /// <param name="content">内容</param>
        private void Print(string content)
        {
            Response.ContentType = "text/plain";
            Response.Write(content);
        }

        /// <summary>
        /// 获取联系人
        /// </summary>
        private void GetMsgUsers()
        {
            string AddrListClassIDArray = ConfigurationManager.AppSettings["AddrListClassIDArray"];
            string AddrListRoleIDArray = ConfigurationManager.AppSettings["AddrListRoleIDArray"];
            int[] ClassIDArray = AddrListClassIDArray.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select<string, int>(s => int.Parse(s)).ToArray();
            int[] RoleIDArray = AddrListRoleIDArray.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select<string, int>(s => int.Parse(s)).ToArray();

            var MsgList = bsc.GetMsgUser(User.AreaCode, ClassIDArray, RoleIDArray);
            Print(MsgList);
        }

        /// <summary>
        /// 获取已发送消息
        /// </summary>
        private void GetSentMsgs()
        {
            var MsgList = bsc.GetMsgs(null, User.CorpUserGuid, AppID, null, null, false, User.CurrentArea);
            Print(JsonConvert.SerializeObject(MsgList));
        }
        
        /// <summary>
        /// 删除信息
        /// </summary>
        private void MsgsDelete()
        {
            bool rst = bsc.MsgsDelete(User.CorpUserGuid, AppID, Request["MsgIDs"]);
            Print(rst ? "success" : "fail");
        }

        /// <summary>
        /// 获取消息简讯
        /// </summary>
        private void GetLetterBrief()
        {
            var list = bsc.GetLetterBrief(User.CorpUserGuid, 5, AppID);
            var dtoList = list.Select(m => new 
            {
                ID = m.ID,
                MsgText = m.MsgText,
                Receiver = m.Receiver,
                Sender = m.Sender,
                SendTime = m.SendTime.ToString()
            });

            Print(JsonConvert.SerializeObject(dtoList));
        }

        #endregion
    }
}